<?php
class AdPost extends AppModel {

	public $name = 'AdPost';
    public $validate = array(
        'title' =>
            array(
                'minlength' => array('rule' => array('minLength', 1)),
                'maxlength' => array('rule' => array('maxLength', 100))
            ),
        'description' =>
            array(
                'minlength' => array('rule' => array('minLength', 1)),
                'maxlength' => array('rule' => array('maxLength', 10000))
            ),
        'price' =>
            array(
                'numonly' => array(
                    'rule'       => array('money', 'left'),
                    'allowEmpty' => true
                )
            )
    );
    public $belongsTo = array(
        'AdCategory' => array(
            'fields'       => 'id, parent, category',
            'counterCache' => true
            //'counterScope' => array('active' => 1)
        ),
        'Location'   => array(
            'counterCache' => true
        ),
        'User'       => array(
            'fields' => 'id, email'
        ),
        'DefaultImage' => array(
            'className'  => 'AdImage',
            'foreignKey' => 'ad_image_id',
            'fields'     => 'id, filename'
        )
    );
    public $hasMany = array(
        'AdImage' =>
            array(
                'className'  => 'AdImage',
                'foreignKey' => 'ad_post_id',
                'limit'      => 5,
                'dependent'  => true
            )
    );


    public function saveDefaultImage ($id, $image_id) {
        $sql = 'UPDATE `'.$this->table.'` SET `ad_image_id`='.$image_id.' ' .
               'WHERE `id`='.$id.' AND (`ad_image_id` IS NULL OR `ad_image_id`="")';
        return $this->query($sql);
    } // saveDefaultImage

    public function deletePost ($id) {
        $image = new AdImage();

        $dir = WWW_ROOT.'img'.DS.'images'.DS;
        $sql = 'SELECT `filename` FROM '.$image->table.' ' .
               'WHERE `ad_post_id`='.$id;
        $res = $image->query($sql);
        $b   = $this->del($id);

        if ($b) { // record deleted, remove all associated images from server
            foreach ($res as $models) {
                $filename = $models['ad_images']['filename'];
                @unlink($dir.$filename);
                @unlink($dir.'s_'.$filename);
            }
        }

        return $b;
    } // deletePost
} // AdPost
?>